<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, watch } from 'vue';
import dayjs from 'dayjs';
import { vcpget } from '@/service/api/modules/erp';

const chartRef = ref();
const currentDate = dayjs();
const selectedYear = ref(currentDate.year());
const selectedMonthIndex = ref(currentDate.month()); // 月份从0开始
let myChart;
const monthArr = ref(
  Array.from({ length: 12 })
    .fill(0)
    .map((_, i) => (i + 1 > 9 ? `${selectedYear.value}-${i + 1}` : `${selectedYear.value}-0${i + 1}`)) // 确保月份格式正确
);
const selectedMonth = ref(monthArr.value[selectedMonthIndex.value]);

const fetchData = month => {
  vcpget('/erpsyncmes/baseData/bugRequestLog/view/imageDatas', { yearMonth: `${month}` }).then(res => {
    console.log(res);
    const data = res.data.filter(v => v.bugLogViewdetails.length > 0);
    const option = {
      title: {
        // 显示年份跟月份
        text: `月度缺陷数量统计（${month}）月`,
        // text: `月度缺陷数量统计（${month.slice(5)} 月）`, // 调整显示文本
        left: 'center',
        top: 10
      },
      toolbox: {
        show: true,
        feature: {
          dataView: { readOnly: false },
          restore: {},
          saveAsImage: {}
        }
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 30
        },
        {
          start: 0,
          end: 30
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        // data: ['缺陷类型1', '缺陷类型2', '缺陷类型3'],
        left: 'center',
        top: 30
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.day)
      },
      yAxis: {
        type: 'value',
        name: '单位（PCS）',
        nameGap: 25,
        nameTextStyle: {
          fontSize: 16
        },
        axisLine: { show: true, symbol: ['none', 'arrow'], symbolSize: [6, 7] }
      },
      series: [0, 1, 2].map(index => {
        return {
          // name: `缺陷类型${index + 1}`, // 确保每个系列都有 name 属性
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            textStyle: {
              fontSize: '12px',
              color: 'grey'
            }
          },
          data: data.map((v, i) => [i, v.bugLogViewdetails[index].pcsQty, v.bugLogViewdetails[index].ltBugName]),
          encode: {
            tooltip: [2, 1]
          }
        };
      })
    };

    if (data.length === 0) {
      option.title.text = `月度缺陷数量统计（${month.slice(5)} 月） - 暂无数据`;
      option.series = [];
      option.graphic = [
        {
          type: 'text',
          left: 'center',
          top: 'center'
        }
      ];
    }
    myChart.setOption(option);
  });
};

const handleClick = month => {
  selectedMonth.value = month;
  selectedMonthIndex.value = monthArr.value.indexOf(month);
  fetchData(month);
};

const fetchYearData = year => {
  // 点击时候边框样式变红

  selectedYear.value = year;
  monthArr.value = Array.from({ length: 12 })
    .fill(0)
    .map((_, i) => (i + 1 > 9 ? `${year}-${i + 1}` : `${year}-0${i + 1}`)); // 确保月份格式正确
  selectedMonthIndex.value = currentDate.year() === year ? currentDate.month() : 0;
  selectedMonth.value = monthArr.value[selectedMonthIndex.value];
  fetchData(selectedMonth.value);
};

onMounted(() => {
  myChart = echarts.init(chartRef.value);
  window.addEventListener('resize', myChart.resize);
  const startYear = 2020;
  const years = Array.from({ length: currentDate.year() - startYear + 1 }, (_, i) => startYear + i);

  // 初始化年份选择器
  selectedYear.value = currentDate.year();
  monthArr.value = Array.from({ length: 12 })
    .fill(0)
    .map((_, i) => (i + 1 > 9 ? `${selectedYear.value}-${i + 1}` : `${selectedYear.value}-0${i + 1}`)); // 确保月份格式正确
  selectedMonthIndex.value = currentDate.month();
  selectedMonth.value = monthArr.value[selectedMonthIndex.value];

  // 获取当前月份
  const currentMonth = currentDate.format('YYYY-MM');
  const currentIndex = monthArr.value.indexOf(currentMonth);

  if (currentIndex !== -1) {
    selectedMonth.value = monthArr.value[currentIndex];
    selectedMonthIndex.value = currentIndex;
    fetchData(currentMonth);
  } else {
    // 如果找不到当前月份，则默认选择第一个月份
    fetchData(monthArr.value[0]);
  }
});

watch(selectedYear, newYear => {
  monthArr.value = Array.from({ length: 12 })
    .fill(0)
    .map((_, i) => (i + 1 > 9 ? `${newYear}-${i + 1}` : `${newYear}-0${i + 1}`)); // 确保月份格式正确
  selectedMonthIndex.value = currentDate.year() === newYear ? currentDate.month() : 0;
  selectedMonth.value = monthArr.value[selectedMonthIndex.value];
  fetchData(selectedMonth.value);
});
</script>

<template>
  <div class="chart-container">
    <div class="month">
      <div class="year-selector">
        <select v-model="selectedYear" @change="fetchYearData(selectedYear)">
          <option
            v-for="year in Array.from({ length: currentDate.year() - 2020 + 1 }, (_, i) => 2020 + i)"
            :key="year"
            :value="year"
            class="year-options"
          >
            {{ year }}
          </option>
        </select>
      </div>
      <ACard
        v-for="(month, index) in monthArr"
        :key="index"
        title=""
        class="month-item iconfont icon-keshihuakanban"
        :class="{ active: index === selectedMonthIndex }"
        @click="handleClick(month)"
      >
        {{ month.slice(5) }} 月
      </ACard>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  height: 500px;
  display: flex;
}
.month {
  width: 30%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-sizing: border-box;
}
.year-selector {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.year-selector select {
  width: 100%;
  padding: 8px;
  font-size: 16px;
  border: 2px solid rgb(225, 235, 253);
  border-radius: 4px;
  text-align: center;
  font-style: italic;
  font-size: 18px;
  font-weight: bold;
  color: rgb(149, 179, 236);
  appearance: none;
}

.year-selector select:focus {
  outline: none; /* 去除默认的聚焦样式 */
  border-color: rgb(149, 179, 236); /* 设置聚焦时的边框颜色为红色 */
}
.month-item {
  width: calc(100% / 3 - 10px); /* 减少宽度以适应一行三个盒子 */
  height: 90px; /* 增加高度以便更好地居中显示 */
  border-radius: 6px;
  text-align: center;
  background-color: rgb(225, 235, 253);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  border: 1px solid rgb(225, 235, 253);
  margin: 5px;
  cursor: pointer;
  font-weight: 550;
  color: rgb(119, 159, 235);
}

.active {
  background-color: rgb(179, 200, 238);
}
.month-item:hover {
  background-color: rgb(179, 200, 238);
  transform: scale(1.05);
}
.chart {
  width: 70%;
  height: 100%;
}
</style>
